<?php
/**
 * Author: bluer
 * Date: 6/22/16
 */
class Note {
    /**
     * 全局失效的知识点列表
     * @var array
     */
    protected static $_badNotes;

    /**
     * 更新指定用户的知识点列表
     *
     * @param int $userId
     * @return bool
     */
    public function updateUserNotes($userId) {
        global $cmsdb;

        $noteVersion = $cmsdb->table($cmsdb->options)->cache()
            ->where('option_name', 'note_list_version')
            ->limit(1)
            ->value('option_value');
        if (!$noteVersion) return false;

        $user = $cmsdb->table($cmsdb->qbUserData)->cache()
            ->select('id','note_info','exam_detail_id')
            ->where('user_id', $userId)
            ->where('note_version', '<', $noteVersion)
            ->first();
        if (!$user) return false;

        $examId = $cmsdb->table($cmsdb->examDetail)->cache()
            ->where('id', $user->exam_detail_id)
            ->value('exam_id');
        if (!$examId) return false;

        $examNotes = getNotesByTestId($examId);
        if (!$examNotes) return false;

        self::$_badNotes = $cmsdb->table($cmsdb->notes)->cache()
            ->where('term_type', 1)
            ->where('term_status', 0)
            ->value('id');

        $data = array('note_version'=>$noteVersion);
        $changed = $this->_updateUserNotes($user->note_info, $examNotes);
        if ($changed) $data['note_info'] = $user->note_info;

        return $cmsdb->table($cmsdb->qbUserData)->where('id', $user->id)->update($data);
    }

    /**
     * 更新用户的知识点列表
     *
     * @param object &$noteInfo 用户当前的知识点
     * @param array &$notes 考试项目当前的知识点
     * @return bool
     */
    private function _updateUserNotes(&$noteInfo, &$notes) {
        $changed = false;
        $newNotes = array();
        foreach ($notes as $n) {
            if (empty(self::$_badNotes) || !in_array($n->note_id, self::$_badNotes)) {
                // 序列格式：array('value'=>1, 'rightCount'=>0, 'totalCount'=>0, 'level'=>0);
                $newNotes[$n->note_id] = array(1,0,0,0,0);
            }
        }

        $userNotes = json_decode($noteInfo, true);
        if (is_array($userNotes)) {
            foreach ($newNotes as $nid => $note) {
                if (key_exists($nid, $userNotes)) {
                    $newNotes[$nid] = $userNotes[$nid];
                    unset($userNotes[$nid]);
                } elseif (!$changed) { // 有新增
                    $changed = true;
                }
            }

            // 有删减
            if (!$changed && !empty($userNotes)) $changed = true;

        } else {
            $changed = true;
        }

        if ($changed) $noteInfo = json_encode($newNotes);

        return $changed;
    }
}